//
//  Created by  fred on 2017/1/12.
//  Copyright © 2016年 Alibaba. All rights reserved.
//

package com.test.aliai;

import com.alibaba.cloudapi.sdk.constant.SdkConstant;
import com.alibaba.cloudapi.sdk.enums.HttpMethod;
import com.alibaba.cloudapi.sdk.model.ApiResponse;
import com.alibaba.cloudapi.sdk.model.HttpClientBuilderParams;
import com.test.aliai.view.BankCardVO;
import com.test.utils.FileUtil;
import com.test.utils.JsonUtil;
import net.coobird.thumbnailator.Thumbnails;

import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

public class BankCardClient extends AbstractAliApi{

    private final static String HOST = "yhk.market.alicloudapi.com";

    private final static String PATH = "/rest/160601/ocr/ocr_bank_card.json";

    public BankCardClient(HttpClientBuilderParams params){
        super(params);
    }

    @Override
    public String getHost() {
        return HOST;
    }

    @Override
    public String getPath() {
        return PATH;
    }

    @Override
    public HttpMethod getHttpMethod() {
        return HttpMethod.POST_BODY;
    }

    public static void main(String[] args) throws Exception {
        HttpClientBuilderParams param = new HttpClientBuilderParams();
        param.setAppKey(Const.ALI_ACCESS_KEY_ID);
        param.setAppSecret(Const.ALI_SECRET);
        BankCardClient client = new BankCardClient(param);
        String fileName = "d:\\bankcard.jpg";
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Thumbnails.of(fileName).scale(1f).outputQuality(0.25f).toOutputStream(out);
        String str64 = FileUtil.getFileBase64(out.toByteArray());
        Map<String, Object> body = new HashMap<>();
        body.put("image", str64);
        String jsonStr = JsonUtil.toJson(body);
        ApiResponse response = client.syncReq(jsonStr.getBytes(SdkConstant.CLOUDAPI_ENCODING));
        String resultStr = new String(response.getBody() , SdkConstant.CLOUDAPI_ENCODING);
        Map<String, Object> map = JsonUtil.jsonToMap(resultStr);
        BankCardVO vo = BankCardVO.build(map);
        System.out.println("isSuccess=" + vo.isSuccess());
        System.out.println("getRegNum=" + vo.getBankName());
        System.out.println("getName=" + vo.getCardNum());
        System.out.println("getBusiness=" + vo.getCardType());
        System.out.println("getType=" + vo.getValidDate());
        System.out.println("isFake=" + vo.isFake());
    }
}